#!/bin/sh

#This file is part of TubeMan
#Copyright Oliver Galvin, 2018
#This script builds TubeMan statically against libcurl, libsqlite and libncurses
#Running this script depends on curl, tar, gunzip, mingw/musl, make, cc, sh

case $2 in
	win32)	host="i386-w64-mingw32" ;;
	win64)	host="x86_64-w64-mingw32" ;;
	musl)	host="x86_64-pc-linux-gnu"
		export CC="musl-gcc -static" ;;
	*)	echo "Statically cross compiling TubeMan for different targets"
		echo "---"
		echo "Usage:"
		echo "$1 win32 - 32 bit windows cross compile"
		echo "$1 win64 - 64 bit windows cross compile"
		echo "$1 musl - linux musl build"
		exit ;;
esac

export CFLAGS="-Os"
export LDFLAGS="-Wl,-s"

builddir="static"
curlver="7.61.0"
sqlitever="3240000"
ncursesver="6.1"
sslver="2.4.7"
ext=".tar.gz"

mkdir "$builddir"
cd "$builddir" || exit

file="libressl-${sslver}"
echo "Building $file"
url="https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/${file}${ext}"
curl -Os "$url"
tar -xzf "${file}${ext}"
cd "$file" || exit
./configure --disable-shared --host="$host"
make
export LDFLAGS="${LDFLAGS} -L${file}/lib"
export CFLAGS="${CFLAGS} -I${file}/include"
cd ..
exit

file="curl-${curlver}"
echo "Building $file"
url="https://curl.haxx.se/download/${file}${ext}"
curl -Os "$url"
tar -xzf "${file}${ext}"
cd "$file" || exit
./configure \
	--disable-shared --disable-verbose \
	--disable-versioned-symbols --disable-manual \
	--disable-cookies --disable-ldap \
	--without-librtmp --without-libidn \
	--without-libidn2 --without-librtsp \
	--without-zlib --disable-thread \
	--disable-ipv6 --disable-ares \
	--disable-ftp --disable-tftp \
	--disable-dict --disable-gopher \
	--disable-imap --disable-pop3 \
	--disable-rtsp --disable-smb \
	--disable-smts --disable-smtp \
	--disable-telnet --host="$host"
make
export LDFLAGS="${LDFLAGS} -L${file}/lib/.libs"
export CFLAGS="${CFLAGS} -I${file}/include"
cd ..

file="sqlite-autoconf-${sqlitever}"
echo "Building $file"
url="https://www.sqlite.org/2018/${file}${ext}"
curl -Os "$url"
tar -xzf "${file}${ext}"
cd "$file" || exit
./configure \
	--disable-shared \
	--disable-dynamic-extensions \
	--disable-fts5 \
	--disable-json1 \
	--host="$host"
make libsqlite3.la
export LDFLAGS="${LDFLAGS} -L${file}/.libs"
export CFLAGS="${CFLAGS} -I${file}"
cd ..

file="ncurses-${ncursesver}"
echo "Building $file"
url="ftp://ftp.gnu.org/gnu/ncurses/${file}${ext}"
curl -Os "$url"
tar -xzf "${file}${ext}"
cd "$file" || exit
./configure \
	--without-ada \
	--without-cxx \
	--without-cxx-binding \
	--without-manpages \
	--without-debug \
	--disable-big-core \
	--host="$host"
make
export LDFLAGS="${LDFLAGS} -L${file}/lib"
export CFLAGS="${CFLAGS} -I${file}/include"
cd ..
